//
//  xsSelectDigitalRobotCollectionView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/8/30.
//

#import "xsSelectDigitalRobotCollectionView.h"
//#import "Masonry.h"
@interface xsSelectDigitalRobotCollectionView()<UICollectionViewDelegate,UICollectionViewDataSource>

// 视频比例 aspectRatio    视频比例 现在只有竖屏 传1就行   categoryId： 1是男的 2是女的 0是全部
@property (nonatomic,assign)NSInteger aspectRatioInt;
@property (nonatomic,assign)NSInteger categoryIdInt;

@property (nonatomic,strong) UIView *tableEmptyView;
@property (nonatomic,weak) UIImageView * tableEmptyImage;
@property (nonatomic,weak) UILabel * tableEmptyLabel;
@property (nonatomic,weak) UIButton *covertableEmptyViewButton;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic,assign)CGSize cellSize9_16;

@end

@implementation xsSelectDigitalRobotCollectionView


- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
// 视频比例 aspectRatio    视频比例 现在只有竖屏 传1就行   categoryId： categoryId： 1是男的 2是女的 0是我的
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout withAspectRatio:(NSInteger)aspectRatio withCategoryId:(NSInteger)categoryId{
    
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if(self){
        self.delegate = self;
        self.dataSource = self;
        self.aspectRatioInt  = aspectRatio;
        self.categoryIdInt = categoryId;
        self.page = 1;
        [self getSize9_16];
        
        self.backgroundColor = UIColor.clearColor;//COLOR_VCViewBgcolor;
        
        xsSelectDigitalRobotCollectionViewCellModel *md = [xsSelectDigitalRobotCollectionViewCellModel new];
        md.previewImage = @"bossIPDefaultImage";
//        if(i!=0){
//            md.isAddType = NO;
//        }
//        else{
//            md.isAddType = YES;
//        }
        md.isClickFreeCustom = YES;
        [self.dataArray addObject:md];
        
        
        //        //注册cell
        [self registerClass:[xsSelectDigitalRobotCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([xsSelectDigitalRobotCollectionViewCell class])];
        [self registerClass:[xsSelectDigitalRobotCollectionViewHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([xsSelectDigitalRobotCollectionViewHeadView class])];
        
        [self addSubview:self.tableEmptyView];
        [self.tableEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            //            make.size.mas_equalTo(CGSizeMake(90, 90+5+21));
            make.size.mas_equalTo(CGSizeMake(250, 250));
        }];
        
        XSWeakSelf;
        self.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            
            weakSelf.page = 1;
            [weakSelf.dataArray removeAllObjects];
            
            xsSelectDigitalRobotCollectionViewCellModel *md = [xsSelectDigitalRobotCollectionViewCellModel new];
            md.previewImage = @"bossIPDefaultImage";
    //        if(i!=0){
    //            md.isAddType = NO;
    //        }
    //        else{
    //            md.isAddType = YES;
    //        }
            md.isClickFreeCustom = YES;
            [weakSelf.dataArray addObject:md];
            
            [weakSelf getNumberPeopleDataWithAspectRatio:aspectRatio withCategoryId:categoryId];
            
        }];

//        self.mj_footer= [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
//            ++self.page;
//            [self getNumberPeopleDataWithAspectRatio:aspectRatio withCategoryId:categoryId];
//        }];
        
        
//        [self getNumberPeopleDataWithAspectRatio:aspectRatio withCategoryId:categoryId];
        
        [self.mj_header beginRefreshing];
        
    }
    
    return self;
}

- (void)getSize9_16{
    
    // 获取self.topImgBgView.frame  16:9最佳宽高
        CGFloat loveW9  = 9.0*3.0;
        CGFloat loveH16 = 16.0*3.0;
        BOOL xsIsBrek = NO;
        CGFloat topImgBgViewW = kScreenW-20.0-20.0;
        CGFloat count = 1.0;
        while (!xsIsBrek) {
                
            CGFloat tempLoveW9 = loveW9 *count;
            CGFloat tempLoveH16 = loveH16 *count;
            
            if(tempLoveW9<topImgBgViewW){
                count=count+1.0;
            }
            else{
                xsIsBrek = YES;
            }
            NSLog(@"loveW9==%f\n",loveW9);
            NSLog(@"loveH16==%f\n",loveH16);
        }
        count = count-1;
    // 108 192
    self.cellSize9_16 = CGSizeMake(loveW9*count, loveH16*count);
    NSLog(@"cellSize9_16==%@\n",NSStringFromCGSize(self.cellSize9_16));//cellSize9_16=={324, 576}
}

#pragma mark - UICollectionViewDataSource
//一共有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//每一组有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    self.tableEmptyView.hidden = self.dataArray.count;
    return self.dataArray.count;
}

//每一个cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    xsSelectDigitalRobotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([xsSelectDigitalRobotCollectionViewCell class]) forIndexPath:indexPath];
    
    if (indexPath.row<self.dataArray.count) {
        cell.model = self.dataArray[indexPath.item];
    }
    cell.backgroundColor = UIColor.clearColor;
    cell.contentView.backgroundColor = UIColor.clearColor;
//    cell.layer.cornerRadius = 6.0;
//    cell.layer.masksToBounds = YES;
    
    return cell;
}

//和tableView差不多, 可设置头部和尾部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        xsSelectDigitalRobotCollectionViewHeadView *headerView = [self dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([xsSelectDigitalRobotCollectionViewHeadView class]) forIndexPath:indexPath];
        headerView.backgroundColor = UIColor.clearColor;
        return headerView;
    }
//    else if([kind isEqualToString:UICollectionElementKindSectionFooter])
//    {
//        
//    }
    return nil;
}


//每一个分组的上左下右间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
}

//头部视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(self.frame.size.width, 45.0);
    return CGSizeMake(self.frame.size.width, 0.10);
}


//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //CGFloat margin = 5.0*4.0;
    
    
    CGFloat itemW =  self.cellSize9_16.width/3.0;//(self.frame.size.width-margin)/3.0;
    CGFloat itemH = self.cellSize9_16.height/3.0;//itemW*(4.0/3.0);
    return CGSizeMake(itemW, itemH);
}

//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    return 4;
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 5;
//}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.item<self.dataArray.count){
        xsSelectDigitalRobotCollectionViewCellModel *model = self.dataArray[indexPath.item];
        
        
        
        
        for (xsSelectDigitalRobotCollectionViewCellModel *tempModel in self.dataArray) {
            if(tempModel.Id!=model.Id){
                tempModel.cellIsBeSelect = NO;
                NSLog(@"tempModel.cellIsBeSelect==%d",tempModel.cellIsBeSelect);
            }
            else{
                tempModel.cellIsBeSelect = !tempModel.cellIsBeSelect;
                NSLog(@"tempModel.cellIsBeSelect--YES==%d",tempModel.cellIsBeSelect);
            }
        }
        [self reloadData];
        
        NSLog(@"model.previewImage==%@\n",model.previewImage);
        XSLogMethod
        if([self.delegateDigitalRobot respondsToSelector:@selector(xsDigitalRobotCollectionCellBeClick: withAspectRatio: withCategoryId:)]){
            [self.delegateDigitalRobot xsDigitalRobotCollectionCellBeClick:model withAspectRatio:self.aspectRatioInt withCategoryId:self.categoryIdInt];
        }
    }
}

//
////在开始移动是调动此代理方法
//- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"开始移动");
//    return YES;
//}

////在移动结束的时候调用此代理方法
//- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//    NSLog(@"结束移动");
//
//}


// type 图片类型 1官方图片 2用户图片
//- (void)getDataWithType:(NSInteger)type{
//    
//    XSWeakSelf;

//    
//    NSDictionary *pramerDict = @{@"page":@"1",
//                                 @"limit":@"100",
//                                 @"type":[NSString stringWithFormat:@"%ld",type],
//                                 @"aspectRatio":@"1"};
//    [[ZYFDataManager sharedInstance] POST:@"https://mall219.writemall.com/bossapi/backgroundImage/list" dict:pramerDict succeed:^(id data) {
//        
//        NSLog(@"getDataWithType--data==%@\n",data);
//        
//        NSDictionary *dictData = data;
//        if([dictData isKindOfClass:[NSDictionary class]]){
//            if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
//                NSInteger codeInt = [dictData[@"code"] integerValue];
//                if(codeInt==200){
//                    
//                    if([dictData[@"data"] isKindOfClass:[NSDictionary class]]){
//                        NSDictionary *dictData2 = dictData[@"data"];
//                        if([dictData2[@"data"] isKindOfClass:[NSArray class]]){
//                            NSArray *dataArr3  = dictData2[@"data"];
//                            
//                            if(dataArr3.count>0){
////                                if(type==1){
////                                    
////                                }
////                                else if(type==2){
////                                    
////                                }
////                                else{
////                                    
////                                }
//                                for (int ii=0; ii<dataArr3.count; ii++) {
//                                    NSDictionary *tempFinalDict = dataArr3[ii];
//                                    xsSelectDigitalRobotCollectionViewCellModel *md = [xsSelectDigitalRobotCollectionViewCellModel yy_modelWithDictionary:tempFinalDict];
//                                    md.isAddType = NO;
//                                    //md.url = tempFinalDict[@"url"];
//                                    if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
//                                       [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
//                                       NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
//                                        md.Id = [tempIdStr integerValue];
//                                    }
//                                    [weakSelf.dataArray addObject:md];
//                                }
//                                
//                                dispatch_async(dispatch_get_main_queue(), ^{
//                                    [weakSelf reloadData];
//                                });
//                            }
//                        }
//                    }
//                    
//                }
//            }
//        }
//        
//        
//    } failure:^(NSDictionary *error) {
//        NSLog(@"getDataWithType--error.description==%@\n",error.description);
//    }];
//}

// 视频比例 aspectRatio    视频比例 现在只有竖屏 传1就行   categoryId： 1是男的 2是女的 0是全部
- (void)getNumberPeopleDataWithAspectRatio:(NSInteger)aspectRatio withCategoryId:(NSInteger)categoryId
{
//
    
    XSWeakSelf;
   
    
    NSDictionary *pramerDict = @{@"page":[NSString stringWithFormat:@"%ld",self.page],
                                 @"limit":@"100",
                                 @"categoryId":[NSString stringWithFormat:@"%ld",categoryId],
                                 @"aspectRatio":[NSString stringWithFormat:@"%ld",aspectRatio]};
//    @"https://mall219.writemall.com/bossapi/digitalHuman/pageList"
    NSString *requestUrlString = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"digitalHuman/pageList"];
    [[ZYFDataManager sharedInstance] POST:requestUrlString dict:pramerDict succeed:^(id data) {
        
        
        if(categoryId==0){
            NSLog(@"老板IP模板-全部--data==%@\n",data);
        }
        else if(categoryId==1){
            NSLog(@"老板IP模板-男性--data==%@\n",data);
        }
        else if(categoryId==2){
            NSLog(@"老板IP模板-女性--data==%@\n",data);
        }
        
        NSDictionary *dictData = data;
        if([dictData isKindOfClass:[NSDictionary class]]){
            if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
                NSInteger codeInt = [dictData[@"code"] integerValue];
                if(codeInt==200){
                    
                    if([dictData[@"data"] isKindOfClass:[NSDictionary class]]){
                        NSDictionary *dictData2 = dictData[@"data"];
                        if([dictData2[@"data"] isKindOfClass:[NSArray class]]){
                            NSArray *dataArr3  = dictData2[@"data"];
                            
                            if(dataArr3.count>0){
                                for (int ii=0; ii<dataArr3.count; ii++) {
                                    NSDictionary *tempFinalDict = dataArr3[ii];
                                    xsSelectDigitalRobotCollectionViewCellModel *md = [xsSelectDigitalRobotCollectionViewCellModel yy_modelWithDictionary:tempFinalDict];
                                    md.isClickFreeCustom = NO;
                                    md.cellIsBeSelect = NO;
                                    if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
                                       [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
                                       NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
                                        md.Id = [tempIdStr integerValue];
                                    }
                                    md.aspectRatio = weakSelf.aspectRatioInt;
                                    md.categoryId = weakSelf.categoryIdInt;
                                    [weakSelf.dataArray addObject:md];
                                }
                                
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [weakSelf stopEndRefresh:weakSelf.dataArray];
                                });
                            }
                            else{
                               
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [weakSelf stopEndRefresh:nil];
                                });
                            }
                        }
                        else{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:nil];
                            });
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf stopEndRefresh:nil];
                        });
                    }
                    
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf stopEndRefresh:nil];
                    });
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf stopEndRefresh:nil];
                });
            }
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf stopEndRefresh:nil];
            });
        }
        
        
    } failure:^(NSDictionary *error) {
        NSLog(@"getDataWithType--error.description==%@\n",error.description);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf stopEndRefresh:nil];
        });
    }];
}

- (UIView *)tableEmptyView{
    
    if (!_tableEmptyView) {
        _tableEmptyView = [[UIView alloc] init];
        _tableEmptyView.backgroundColor = UIColor.clearColor;
        
        
        UITapGestureRecognizer *tableEmptyViewRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [_tableEmptyView addGestureRecognizer:tableEmptyViewRecognizer];
        
        UIImageView *tableEmptyImage = [[UIImageView alloc] init];
        tableEmptyImage.image = [UIImage imageNamed:@"CYNotSearchResultData"];
        [_tableEmptyView addSubview:tableEmptyImage];
        tableEmptyImage.backgroundColor = UIColor.clearColor;
        self.tableEmptyImage = tableEmptyImage;
        
        UILabel *tableEmptyLabel = [[UILabel alloc] init];
        tableEmptyLabel.text = @"暂无数据";//kLocalizedString(@"暂无数据");
        tableEmptyLabel.font = [UIFont systemFontOfSize:16];//Font(16);
        tableEmptyLabel.numberOfLines = 0;
        tableEmptyLabel.textAlignment = NSTextAlignmentCenter;
        tableEmptyLabel.textColor = COLOR_HEX(0x999999);
        [_tableEmptyView addSubview:tableEmptyLabel];
        self.tableEmptyLabel = tableEmptyLabel;
        
        tableEmptyImage.userInteractionEnabled = YES;
        tableEmptyLabel.userInteractionEnabled = YES;

        UITapGestureRecognizer *tableEmptyImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [tableEmptyImage addGestureRecognizer:tableEmptyImageRecognizer];

        UITapGestureRecognizer *tableEmptyLabelRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyLabelGestureEvent:)];
        [tableEmptyLabel addGestureRecognizer:tableEmptyLabelRecognizer];
        
        [tableEmptyImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.centerY.equalTo(_tableEmptyView.mas_centerY).offset(-10);
            make.size.mas_equalTo(CGSizeMake(80.55, 86.58));
        }];
        [tableEmptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.top.equalTo(tableEmptyImage.mas_bottom).offset(5);
        }];
        //
        //        UIButton *covertableEmptyViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        covertableEmptyViewButton.backgroundColor = UIColor.purpleColor;//UIColor.clearColor;
        //        [_tableEmptyView addSubview:covertableEmptyViewButton];
        //        self.covertableEmptyViewButton = covertableEmptyViewButton;
        //        XSWeakSelf;
        //        [covertableEmptyViewButton addTapRunWithBlock:^(UIButton * _Nonnull YSBtn) {
        //            if(weakSelf.tableViewNotContentDataBgViewBeClickEvent){
        //                weakSelf.tableViewNotContentDataBgViewBeClickEvent();
        //            }
        //        }];
        
    }
    return _tableEmptyView;
    
}
- (void)tableEmptyImageGestureEvent:(UITapGestureRecognizer *)sender{
    
    [self tableEmptyLabelGestureEvent:sender];
}
- (void)tableEmptyLabelGestureEvent:(UITapGestureRecognizer *)sender{
    
    NSLog(@"tableEmptyLabelGestureEvent");
    
    if(self.dataArray.count<=0){
//        [self getNumberPeopleDataWithAspectRatio:self.aspectRatioInt withCategoryId:self.categoryIdInt];
        [self.mj_header beginRefreshing];
    }
}



#pragma mark - stopEndRefresh
- (void)stopEndRefresh:(NSArray *) array {
    
    if (self.page  == 1) {
        if (self.mj_footer.isRefreshing) {
            [self.mj_footer endRefreshing];
        }
        [self.mj_header endRefreshing];
        [self.mj_footer resetNoMoreData];
    }else {
        if (array.count > 1) {
            [self.mj_footer endRefreshing];
        }else {
            [self.mj_footer endRefreshingWithNoMoreData];
        }
    }
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself reloadData];
    });
}

// 更新数据不是categoryId的数据 改为未选中
- (void)xsDigitalRobotCollectionUpdateCellModelNoSelect{
    
    if(self.dataArray.count>0){
        for (xsSelectDigitalRobotCollectionViewCellModel *tempModel in self.dataArray) {
            tempModel.cellIsBeSelect = NO;
        }
        [self reloadData];
    }
}

@end



